package com.bcts.rrh.drawingboard;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.bcts.rrh.drawingboard.shapeview.PathList;
import com.bcts.rrh.drawingboard.shapeview.Pathview;
import com.bcts.rrh.drawingboard.shapeview.Triangle;


public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable {
    private static final int NONE = 0;// 原始

    public static final int STROKE_TYPE_ERASER = 1;//橡皮檫模式
    public static final int STROKE_TYPE_DRAW = 2;//画笔模式
    public static final int STROKE_TYPE_LINE = 3;//划线模式
    public static final int STROKE_TYPE_CIRCLE = 4;//画圆模式
    public static final int STROKE_TYPE_triangle = 5;//画三角形形模式
    public static final int STROKE_TYPE_RECTANGLE = 6;//画矩形模式
    public static final int MOVE = 7;// 拖动
    public static final int ROTATE=8;// 旋转
    public static final int ZOOM = 9;// 放大
    public static final int FILL=10;//  填充
    public static int strokeType=STROKE_TYPE_DRAW;//模式选择，橡皮檫1，画笔2，线条3，圆形4，矩形5等,初始状态是画笔状态
    public int TriangleState=0;//画三角形的状态，0代表不用画，1代表画第一条边，2代表画整个三角形
    public int mWidth, mHeight;//屏幕的高度和宽度

    private Paint mEraserPaint;//橡皮檫的画笔
    private Paint mPaint;//写字时的画笔
    private Path mPath;//路线
    private SurfaceHolder msurfaceHolder=null;//surfaceView的 控制器
    private Canvas mCanvas;
    private float mX, mY;

    private boolean running=true;//surfaceView是否多线程运行


    public MySurfaceView(Context context) {
        super(context);
        setScreenWH();

        msurfaceHolder = getHolder();//获取holder
        msurfaceHolder.addCallback(this);
        initPaint();//初始化
    }

    private void initPaint() {
        setWillNotDraw(false);//表示当前控件每次重绘时，都需要绘制该控件

        //设置写字画笔
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setColor(Constants.penColor);
        mPaint.setStrokeWidth(5);
        //设置橡皮擦的画笔
        mEraserPaint = new Paint();
        mEraserPaint.setAlpha(0);
        //下面这句代码是橡皮擦设置的重点
        mEraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        //上面这句代码是橡皮擦设置的重点
        mEraserPaint.setAntiAlias(true);
        mEraserPaint.setDither(true);
        mEraserPaint.setStyle(Paint.Style.STROKE);
        mEraserPaint.setStrokeJoin(Paint.Join.ROUND);
        mEraserPaint.setStrokeWidth(30);
        mPath = new Path();
//        BmpDST = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);//创建一个屏幕大小的位图
//        mCanvas = new Canvas(BmpDST);
        draw();

        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);
    }

    private void setScreenWH() {//获取屏幕的宽度和高度
        DisplayMetrics dm =  this.getResources().getDisplayMetrics();
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
    }
    public void setMode(int mode)//设置模式
    {
        this.strokeType=mode;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        running=true;
        new Thread(this).start();//新建一个线程供surface绘图

    }

    @Override
    public void run() {
        int SLEEP_TIME=100;//线程睡眠时间
        //每隔100毫秒执行一次draw方法
        while (running){
            draw();
            try {
                Thread.sleep(SLEEP_TIME);

            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void draw() {//画画笔
        try {
            //锁定画布并返回画布对象
            mCanvas = msurfaceHolder.lockCanvas();
            mCanvas.drawColor(Color.rgb(25,67,56));
            pathList.draw(mCanvas);

        }catch (Exception e) {
        } finally {
            //当画布内容不为空时才提交显示
            if (mCanvas != null)
                msurfaceHolder.unlockCanvasAndPost(mCanvas);
        }
    }
    private void paintline(float x1,float y1,float x2, float y2){
        //锁定画布并返回画布对象
        mCanvas=msurfaceHolder.lockCanvas();
        mCanvas.drawColor(Color.rgb(25,67,56));
        mCanvas.drawLine(x1,y1,x2,y2, mPaint);
        msurfaceHolder.unlockCanvasAndPost(mCanvas);

    }
    //清屏
    private void clearCavas() {
        msurfaceHolder.lockCanvas(new Rect(0, 0, 0, 0));
        mCanvas.drawColor(Color.rgb(25,67,56));
        msurfaceHolder.unlockCanvasAndPost(mCanvas);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }
    Pathview pathview;
    PathList pathList=new PathList();
    Triangle triangle;
    float x1,y1,x2,y2,x3,y3;
    boolean moveable=false;//是否可以移动
    @Override
    public boolean onTouchEvent( MotionEvent event) {
        float x = event.getX();//获取手指触碰点的X坐标
        float y = event.getY();//获取手指触碰点的Y坐标
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:////用户又使用一个手指触摸到屏幕上，也就是说，在已经有一个触摸点的情况下，有新出现了一个触摸点。
                touch_start(x, y);
                break;
            case MotionEvent.ACTION_MOVE://用户手指的移动
                touch_move(x, y);
                break;
            case MotionEvent.ACTION_UP://用户的手指离开屏幕
                //draw();
                touch_up(x, y);
                break;
        }
        return true;
    }



    private void touch_start(float x, float y) {//手指触屏时
        //mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        switch (strokeType){
            case STROKE_TYPE_DRAW://画笔
                pathview=new Pathview();
                pathview.setType(strokeType);
                pathview.path.moveTo(mX, mY);
                pathList.addPathView(pathview);
                draw();
                break;
            case STROKE_TYPE_ERASER://橡皮擦
                pathList.removePathView(x,y);
                break;
            case STROKE_TYPE_CIRCLE://划椭圆
                pathview=new Pathview();
                pathview.setType(strokeType);
                pathList.addPathView(pathview);
                break;
            case STROKE_TYPE_triangle://画三角形
                if(TriangleState==0){
                    TriangleState=1;//画第一条边
                    pathview=new Pathview();//创建新的Pathview对象
                    pathview.setType(strokeType);
                    pathview.point1=new Point((int)x,(int)y);
                    pathview.point2=new Point((int)x,(int)y);
                    pathview.point3=new Point((int)x,(int)y);
                    pathList.addPathView(pathview);
                }
                else if(TriangleState==1){
                    TriangleState=2;//画第二条边
                    pathview.point3=new Point((int)x,(int)y);//设置三角形三个点坐标
                }
                pathview.tripath();
                draw();
                break;
            case STROKE_TYPE_RECTANGLE://画矩形模式
                pathview=new Pathview();//创建新的pathview对象
                pathview.setType(strokeType);
                pathList.addPathView(pathview);
                break;
            case STROKE_TYPE_LINE://划直线
                pathview=new Pathview();
                pathview.setType(strokeType);
                pathList.addPathView(pathview);
                break;
            case MOVE://移动模式
                pathList.moveable(x,y);
                break;
            case FILL://填充模式
                pathList.setFill(x,y);
                break;
            case ROTATE://旋转
                pathList.rotateable(x,y);
                break;
        }
    }

    private void touch_move(float x, float y) {//手指移动时
        switch (strokeType){
            case STROKE_TYPE_DRAW://画笔
                pathview.path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
                mX = x;
                mY = y;
                draw();
                break;
            case STROKE_TYPE_LINE://直线
                pathview.linepath(mX,mY,x,y);
                draw();
                break;
            case STROKE_TYPE_CIRCLE://圆形
                pathview.ovalpath(mX,mY,x,y);
                draw();
                break;
            case STROKE_TYPE_triangle://画三角形
                if(TriangleState==1){
                    pathview.point2=new Point((int)x,(int)y);
                    pathview.point3=new Point((int)x,(int)y);//设置三角形三个点坐标
                }
                else if(TriangleState==2){
                    pathview.point3=new Point((int)x,(int)y);//设置三角形三个点坐标
                }
                pathview.tripath();
                draw();
                break;
            case STROKE_TYPE_RECTANGLE://矩形
                pathview.rectpath(mX,mY,x,y);
                draw();
                break;
            case MOVE://移动模式
                for (Pathview p:pathList.paths){
                    if(p.moveable==true){
                        p.moveView(x,y);
                        break;
                    }
                }
                draw();
                break;
            case ROTATE://旋转模式
                for (Pathview p:pathList.paths){
                    if(p.moveable==true){
                        p.rotateViewMove(x,y);
                        break;
                    }
                }
                draw();
                break;
        }
    }

    private void touch_up(float x, float y) {//手指离开时
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        mPath.lineTo(mX, mY);
        switch (strokeType){
            case STROKE_TYPE_triangle://画三角形
                if(TriangleState==1){
                    TriangleState=2;
                    pathview.point2=new Point((int)x,(int)y);
                    pathview.point3=new Point((int)x,(int)y);//设置三角形三个点坐标
                }
                else if(TriangleState==2){
                   /* Bitmap bitmap=triangle.ChildrenView(mWidth,mHeight);
                    ByteArrayOutputStream os=new ByteArrayOutputStream();
                    *//*
                     * Bitmap.CompressFormat.JPEG 和 Bitmap.CompressFormat.PNG
                     * JPEG 与 PNG 的是区别在于 JPEG是有损数据图像，PNG使用从LZ77派生的无损数据压缩算法。
                     * 这里建议使用PNG格式保存
                     * 100 表示的是质量为100%。当然，也可以改变成你所需要的百分比质量。
                     * os 是定义的字节输出流
                     *
                     * .compress() 方法是将Bitmap压缩成指定格式和质量的输出流
                     *//*
                    bitmap.compress(Bitmap.CompressFormat.PNG,100,os);
                    dBservice.savebitmap(STROKE_TYPE_triangle,os.toByteArray());*/
                    TriangleState=0;
                    pathview.point3=new Point((int)x,(int)y);//设置三角形三个点坐标
                }
                pathview.tripath();
                draw();
                break;
        }
    }

    public void reset(){
        pathList.clear();
        /*Paint p = new Paint();
        //清屏
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        mCanvas.drawPaint(p);
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        invalidate();*/
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

        running=false;
    }
}

